<!--
 * @Description: 产品列表页面 - 提供产品数据的管理和展示功能，支持路由参数动态初始化和排序
 * @Author: lujq
 * @Date: 2024-12-21
 * @LastEditors: lujq
 * @LastEditTime: 2025-01-05 20:35:00
-->
<template>
  <div class="product-list">
    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入产品名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="产品类别">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择产品类别"
            clearable
            style="width: 150px"
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="真丝面料" value="silk" />
            <el-option label="棉质面料" value="cotton" />
            <el-option label="羊毛面料" value="wool" />
            <el-option label="亚麻面料" value="linen" />
            <el-option label="涤纶面料" value="polyester" />
            <el-option label="混纺面料" value="blend" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-select
            v-model="searchForm.priceRange"
            placeholder="请选择价格区间"
            clearable
            style="width: 150px"
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="0-50元" value="0-50" />
            <el-option label="50-100元" value="50-100" />
            <el-option label="100-200元" value="100-200" />
            <el-option label="200-500元" value="200-500" />
            <el-option label="500元以上" value="500+" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select
            v-model="searchForm.stockStatus"
            placeholder="请选择库存状态"
            clearable
            style="width: 120px"
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="充足" value="sufficient" />
            <el-option label="紧张" value="low" />
            <el-option label="缺货" value="out" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增产品
        </el-button>
        <!-- <el-button type="success" @click="handleBatchImport">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button> -->
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button
          type="danger"
          :disabled="selectedProducts.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </el-card>

    <!-- 产品列表表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="productList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productCode" label="产品编码" width="120" fixed="left" />
        <el-table-column label="产品信息" width="200" fixed="left">
          <template #default="{ row }">
            <div class="product-info">
              <div class="product-image">
                <ImagePreview
                  :src="row.image"
                  :title="row.name"
                  width="50px"
                  height="50px"
                  border-radius="4px"
                />
              </div>
              <div class="product-details">
                <div class="product-name">{{ row.name }}</div>
                <div class="product-spec">{{ row.specification }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="产品类别" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)">{{
              getCategoryName(row.category)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价(元/米)" width="100" align="right">
          <template #default="{ row }">¥{{ row.price.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="stock" label="库存(米)" width="100" align="right">
          <template #default="{ row }">
            <span :class="getStockClass(row.stock)">{{ row.stock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="销量(米)" width="100" align="right" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="120">
          <template #default="{ row }">{{ formatDate(row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleView(row)"> 查看 </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)"> 编辑 </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)"> 删除 </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 产品详情对话框 -->
    <ProductDetailDialog v-model="detailVisible" :product="currentProduct" />

    <!-- 产品表单对话框 -->
    <ProductFormDialog
      v-model="formVisible"
      :product="currentProduct"
      :mode="formMode"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Upload, Download, Delete, Picture } from '@element-plus/icons-vue'
import ProductDetailDialog from './components/ProductDetailDialog.vue'
import ProductFormDialog from './components/ProductFormDialog.vue'
import ImagePreview from './components/ImagePreview.vue'
import { getProductList, deleteProduct, batchDeleteProducts } from '@/api/product'
import type { Product } from '@/types'

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  priceRange: '',
  stockStatus: '',
})

// 数据状态
const loading = ref(false)
const productList = ref<Product[]>([])
const selectedProducts = ref<Product[]>([])
const currentProduct = ref<Product | null>(null)

// 对话框状态
const detailVisible = ref(false)
const formVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0,
})

/**
 * 获取产品类别名称
 * @param {string} category - 类别代码
 * @returns {string} 类别名称
 */
const getCategoryName = (category: string): string => {
  const categoryMap: Record<string, string> = {
    silk: '真丝面料',
    cotton: '棉质面料',
    wool: '羊毛面料',
    linen: '亚麻面料',
    polyester: '涤纶面料',
    blend: '混纺面料',
  }
  return categoryMap[category] || category
}

/**
 * 获取产品类别标签类型
 * @param {string} category - 类别代码
 * @returns {string} 标签类型
 */
const getCategoryTagType = (category: string): string => {
  const typeMap: Record<string, string> = {
    silk: 'danger',
    cotton: 'success',
    wool: 'warning',
    linen: 'info',
    polyester: 'primary',
    blend: '',
  }
  return typeMap[category] || ''
}

/**
 * 获取库存状态样式类
 * @param {number} stock - 库存数量
 * @returns {string} 样式类名
 */
const getStockClass = (stock: number): string => {
  if (stock <= 0) return 'stock-out'
  if (stock <= 100) return 'stock-low'
  return 'stock-normal'
}

/**
 * 格式化日期
 * @param {string} date - 日期字符串
 * @returns {string} 格式化后的日期
 */
const formatDate = (date: string): string => {
  return new Date(date).toLocaleDateString('zh-CN')
}

/**
 * 加载产品列表
 */
const loadProductList = async () => {
  try {
    loading.value = true
    const params: Record<string, any> = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size,
    }
    if (sortBy.value) params.sortBy = sortBy.value
    if (sortOrder.value) params.sortOrder = sortOrder.value

    const response = await getProductList(params)
    console.log('API 响应:', response)

    if (Array.isArray(response.data)) {
      productList.value = response.data
      pagination.total = response.data.length
    } else if (response.data && response.data.list) {
      productList.value = response.data.list
      pagination.total = response.data.total
    } else {
      productList.value = []
      pagination.total = 0
      console.warn('API 返回的数据格式不正确:', response)
    }
  } catch (error) {
    console.error('加载产品列表失败:', error)
    ElMessage.error('加载产品列表失败')
    productList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

/**
 * 处理搜索
 */
const handleSearch = () => {
  pagination.page = 1
  loadProductList()
}

/**
 * 处理重置
 */
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    category: '',
    priceRange: '',
    stockStatus: '',
  })
  pagination.page = 1
  loadProductList()
}

/**
 * 处理新增产品
 */
const handleAdd = () => {
  currentProduct.value = null
  formMode.value = 'add'
  formVisible.value = true
}

/**
 * 处理批量导入
 */
const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

/**
 * 处理导出数据
 */
const handleExport = async () => {
  try {
    // 动态导入xlsx库
    const XLSX = await import('xlsx')

    // 准备导出数据
    const exportData = [
      [
        '产品编码',
        '产品名称',
        '规格',
        '类别',
        '单价(元)',
        '库存(米)',
        '销量(米)',
        '状态',
        '创建时间',
      ],
      ...productList.value.map((product) => [
        product.productCode,
        product.name,
        product.specification,
        getCategoryName(product.category),
        product.price,
        product.stock,
        product.sales,
        product.status === 'active' ? '上架' : '下架',
        formatDate(product.createTime),
      ]),
    ]

    // 创建工作簿
    const workbook = XLSX.utils.book_new()
    const worksheet = XLSX.utils.aoa_to_sheet(exportData)

    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 产品编码
      { wch: 20 }, // 产品名称
      { wch: 15 }, // 规格
      { wch: 12 }, // 类别
      { wch: 12 }, // 单价
      { wch: 12 }, // 库存
      { wch: 12 }, // 销量
      { wch: 8 }, // 状态
      { wch: 15 }, // 创建时间
    ]
    worksheet['!cols'] = colWidths

    XLSX.utils.book_append_sheet(workbook, worksheet, '产品列表')

    // 生成文件名
    const now = new Date()
    const dateStr = now.toISOString().split('T')[0]
    const fileName = `产品列表_${dateStr}.xlsx`

    // 导出文件
    XLSX.writeFile(workbook, fileName)

    ElMessage.success('产品数据导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

/**
 * 处理批量删除
 */
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedProducts.value.length} 个产品吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const productIds = selectedProducts.value.map((product) => product.id)
    await batchDeleteProducts(productIds)
    ElMessage.success('批量删除成功')
    loadProductList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

/**
 * 处理选择变化
 * @param {Product[]} selection - 选中的产品列表
 */
const handleSelectionChange = (selection: Product[]) => {
  selectedProducts.value = selection
}

/**
 * 处理查看产品
 * @param {Product} product - 产品信息
 */
const handleView = (product: Product) => {
  currentProduct.value = product
  detailVisible.value = true
}

/**
 * 处理编辑产品
 * @param {Product} product - 产品信息
 */
const handleEdit = (product: Product) => {
  currentProduct.value = product
  formMode.value = 'edit'
  formVisible.value = true
}

/**
 * 处理删除产品
 * @param {Product} product - 产品信息
 */
const handleDelete = async (product: Product) => {
  try {
    await ElMessageBox.confirm(`确定要删除产品 "${product.name}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await deleteProduct(product.id)
    ElMessage.success('删除成功')
    loadProductList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 处理表单成功
 */
const handleFormSuccess = () => {
  loadProductList()
}

/**
 * 处理分页大小变化
 * @param {number} size - 分页大小
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadProductList()
}

/**
 * 处理当前页变化
 * @param {number} page - 当前页
 */
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadProductList()
}

// 路由实例
const route = useRoute()

// 排序参数（来自路由）
const sortBy = ref<string>('')
const sortOrder = ref<'asc' | 'desc' | ''>('')

/**
 * 根据路由参数初始化筛选和排序
 * @description 支持 query: name, category, priceRange, stockStatus, sortBy, sortOrder, title
 */
const initFromRouteQuery = () => {
  const q = route.query || {}
  // 合并搜索条件
  Object.assign(searchForm, {
    name: typeof q.name === 'string' ? q.name : '',
    category: typeof q.category === 'string' ? q.category : '',
    priceRange: typeof q.priceRange === 'string' ? q.priceRange : '',
    stockStatus: typeof q.stockStatus === 'string' ? q.stockStatus : '',
  })
  // 设置排序
  sortBy.value = typeof q.sortBy === 'string' ? q.sortBy : ''
  sortOrder.value = (q.sortOrder === 'asc' || q.sortOrder === 'desc') ? q.sortOrder : ''

  // 设置动态标题（仅当前页标题，不修改路由meta）
  if (typeof q.title === 'string' && q.title) {
    document.title = `${q.title} - 布匹销售系统`
  }
}

// 首次挂载，读取路由并加载
onMounted(() => {
  initFromRouteQuery()
  loadProductList()
})

// 监听路由变化，自动刷新
watch(
  () => route.fullPath,
  () => {
    initFromRouteQuery()
    pagination.page = 1
    loadProductList()
  },
)
</script>

<style scoped>
.product-list {
  padding: 0;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 16px;
}

.search-form {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  white-space: nowrap;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-details {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-spec {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.stock-normal {
  color: #67c23a;
}

.stock-low {
  color: #e6a23c;
}

.stock-out {
  color: #f56c6c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form .el-form-item {
    margin-bottom: 16px;
  }

  .action-buttons {
    flex-wrap: wrap;
  }

  .el-table {
    font-size: 12px;
  }
}
</style>
